package com.kfm.jdbc.day0327;

import com.kfm.jdbc.day0327.entity.Account;
import com.kfm.jdbc.day0327.entity.Goods;


import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectOneTest {

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/kfm_store";
        String username = "root";
        String password = "";
        DBUtils<Account> dbUtils = new DBUtils<>(url, username, password);

        String sql = "SELECT * FROM account where id = ?";
        Account account = dbUtils.selectOne(sql, new AccountRecover(), 1);
        System.out.println(account);

        DBUtils<Goods> goodsDBUtils = new DBUtils<>(url, username, password);
        sql = "SELECT * FROM goods where goods_no = ?";
        Goods goods = goodsDBUtils.selectOne(sql, new Recover<Goods>() {
            @Override
            public Goods recover(ResultSet resultSet) {
                Goods goods = new Goods();
                try {
                    goods.setGoodsNo(resultSet.getInt("goods_no"));
                    goods.setGoodsName(resultSet.getString("goods_name"));
                    goods.setCost(resultSet.getDouble("cost"));
                    goods.setPrice(resultSet.getDouble("price"));
                    goods.setCount(resultSet.getInt("count"));
                    goods.setCreateTime(resultSet.getDate("create_time"));
                    goods.setCategoryNo(resultSet.getInt("category_no"));
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }

                return goods;
            }
        }, 1);

        System.out.println(goods);

    }
}

class AccountRecover implements Recover<Account> {

    @Override
    public Account recover(ResultSet resultSet) {
        Account account = new Account();
        try {
            account.setId(resultSet.getInt("id"));
            account.setPhone(resultSet.getString("phone"));
            account.setPassword(resultSet.getString("password"));
            account.setType(resultSet.getBoolean("type"));
            account.setName(resultSet.getString("name"));
            account.setPoint(resultSet.getInt("point"));
            account.setMoney(resultSet.getDouble("money"));
            account.setCreateTime(resultSet.getDate("create_time"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return account;
    }
}
